package com.cqb.cn.common.utils;

import com.cqb.cn.mapper.CourseMapper;
import com.cqb.cn.modle.po.Course;
import com.google.gson.*;
import com.cqb.cn.mapper.DemoMapper;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class ReadJSON {

    @Resource
    DemoMapper demoMapper;

    @Resource
    CourseMapper courseMapper;


    public static void main(String[] args) {
        ReadJSON r = new ReadJSON();
        r.testDemo();
    }

    public void testDemo() {
        try {

            JsonParser parser = new JsonParser();  //创建JSON解析器
            JsonObject object = (JsonObject) parser.parse(new FileReader("D:\\test.json"));  //创建JsonObject对象
//            System.out.println("cat="+object.get("cat").getAsString()); //将json数据转为为String型的数据
//            System.out.println("pop="+object.get("pop").getAsBoolean()); //将json数据转为为boolean型的数据
            List list =new ArrayList<>();
            JsonArray array = object.get("course").getAsJsonArray();    //得到为json的数组
            for (int i = 0; i < array.size(); i++) {
                System.out.println("---------------");
                JsonObject subObject = array.get(i).getAsJsonObject();
                Course course = new Course();
                course.setCoursename(subObject.get("name").getAsString());
                course.setId(subObject.get("id").getAsInt());
//                System.out.println("id=" + subObject.get("id").getAsString());
//                System.out.println("name=" + subObject.get("name").getAsString());
                list.add(course);

            }
            int count = courseMapper.batchInsert(list);

        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
